using System.Collections.Generic;
using System.Linq;
using DMS.BEs;
using DMS.DAOs;
using DMS.DTOs;
using DMS.Filters;

namespace DMS.Services.Impl
{
	public class CustomerService : ServiceBase, ICustomerService
	{
		private readonly ICustomerDAO customerDAO;

		public CustomerService(ICustomerDAO customerDAO)
		{
			this.customerDAO = customerDAO;
		}

		public ResultDTO<CustomerDTO> GetCustomerById(int CustomerId)
		{
			Customer customer = customerDAO.GetById(CustomerId);
			if (customer == null)
				return new ResultDTO<CustomerDTO>(null) { Messages = new[] { "Customer not found" } };

			return new ResultDTO<CustomerDTO>(mapperBEtoDTO.Map<Customer, CustomerDTO>(customer));
		}

		public ResultListDTO<CustomerDTO> GetCustomersByContry(string country)
		{
			IList<Customer> customers = customerDAO.GetByFilter(new CustomerFilter() { Country = country });

			IEnumerable<CustomerDTO> items = (from i in customers select mapperBEtoDTO.Map<Customer, CustomerDTO>(i));
			return new ResultListDTO<CustomerDTO>(items.ToArray());
		}

		public ResultDTO<int> Save(CustomerDTO dto)
		{
			Customer be = mapperDTOtoBE.Map<CustomerDTO, Customer>(dto);

			customerDAO.Persist(be);

			return new ResultDTO<int>(be.Id);
		}

		public ResultDTO<bool> DeleteById(int customerId)
		{
			Customer customer = customerDAO.GetById(customerId);
			customerDAO.Delete(customer);
			return new ResultDTO<bool>(true);
		}

		public ResultDTO<CustomerDTO> GetCustomerByFullName(string firstName, string lastName)
		{
			IList<Customer> customers =
				customerDAO.GetByFilter(new CustomerFilter { FirstName = firstName, LastName = lastName });

			if (customers.Count == 0)
				return new ResultDTO<CustomerDTO>(null) { Messages = new[] { "customer not found" } };
			if (customers.Count > 1)
				return new ResultDTO<CustomerDTO>(null) { Messages = new[] { "too many customers" } };

			Customer customer = customers[0];

			return
				new ResultDTO<CustomerDTO>(
					mapperBEtoDTO.Map<Customer, CustomerDTO>(customer));
		}
	}
}